<template>
  <a-modal
    v-model:visible="visible"
    :width="1500"
    centered
    :maskClosable="false"
    destroyOnClose
    @ok="onFinish"
    title="手动生成"
    :confirm-loading="confirmLoading"
  >
    <a-transfer
      v-model:target-keys="targetKeys"
      v-model:selected-keys="selectedKeys"
      :rowKey="(record) => record.id"
      :data-source="dataSource"
      :titles="['视频列表', '选中数据']"
      :list-style="{
        width: '550px',
        height: '500px',
      }"
      @change="handleChange"
      @selectChange="handleSelectChange"
    >
      <template
        #children="{
          direction,
          filteredItems,
          selectedKeys,
          disabled: listDisabled,
          onItemSelectAll,
          onItemSelect,
        }"
      >
        <a-table
          :row-selection="
            getRowSelection({
              disabled: listDisabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
          "
          :columns="direction === 'left' ? leftColumns : rightColumns"
          :data-source="filteredItems"
          size="small"
          :style="{ pointerEvents: listDisabled ? 'none' : null }"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'status'">
              <span v-if="record.status === 0">运行中</span>
              <span v-else-if="record.status === 1">成功</span>
              <span v-else>失败</span>
            </template>
            <template v-if="column.key === 'sort'">
              <span>{{ index + 1 }}</span>
            </template>
            <template v-if="column.key === 'operation'">
              <div class="table-button">
                <a-button size="small" @click="toUp(record, index)" v-if="index !== 0">
                  <template #icon><UpOutlined /></template>
                </a-button>
                <a-button
                  size="small"
                  @click="toDown(record, index)"
                  v-if="index !== targetKeys.length - 1"
                >
                  <template #icon><DownOutlined /></template>
                </a-button>
              </div>
            </template>
          </template>
        </a-table>
      </template>
    </a-transfer>
  </a-modal>
</template>

<script>
import { onMounted, reactive, toRefs, ref, watch } from "vue";
import { message } from "ant-design-vue";
import { getVideoTaskList, clipsVideoTask } from "@/api/marathon";
import { DownOutlined, UpOutlined } from "@ant-design/icons-vue";

const leftColumns = [
  {
    title: "id",
    dataIndex: "id",
    key: "id",
    width: 50,
  },
  {
    title: "标识名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 100,
  },
];

const rightColumns = [
  {
    title: "顺序",
    dataIndex: "sort",
    key: "sort",
    width: 50,
  },
  {
    title: "id",
    dataIndex: "id",
    key: "id",
    width: 50,
  },
  {
    title: "标识名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 80,
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
    width: 80,
  },
];

export default {
  name: "VideoProduceModal",
  props: {
    modalVisible: {
      type: Boolean,
      default: false,
    },
    detail: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    DownOutlined,
    UpOutlined,
  },
  setup(props, { emit }) {
    onMounted(() => {
      init();
    });
    const init = () => {
      getVideos();
    };

    const state = reactive({
      confirmLoading: false,
      visible: ref(props.modalVisible),
      dataSource: [],
      targetKeys: [],
      selectedKeys: [],
    });

    watch(
      () => props.modalVisible,
      (value) => {
        if (!value) {
          resetFields();
        } else {
          getVideos();
        }
        state.visible = value;
      }
    );

    const getVideos = () => {
      const dto = {
        pageNumber: 1,
        pageSize: 9999,
      };
      getVideoTaskList(dto).then((res) => {
        if (res.result === true) {
          let { responseList = [] } = res?.data;
          state.dataSource = responseList;
        } else {
          message.error("获取视频列表失败：" + res.message);
        }
      });
    };

    const resetFields = () => {
      state.targetKeys = [];
      state.selectedKeys = [];
    };

    const handleCancel = () => {
      emit("cancel");
    };

    const handleChange = (nextTargetKeys, direction, moveKeys) => {
      console.log("targetKeys: ", nextTargetKeys);
      console.log("direction: ", direction);
      console.log("moveKeys: ", moveKeys);
    };
    const handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
      console.log("sourceSelectedKeys: ", sourceSelectedKeys);
      console.log("targetSelectedKeys: ", targetSelectedKeys);
    };

    const getRowSelection = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }) => {
      return {
        getCheckboxProps: (item) => ({
          disabled: disabled || item.disabled,
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({ key }) => key);
          onItemSelectAll(treeSelectedKeys, selected);
        },
        onSelect({ key }, selected) {
          onItemSelect(key, selected);
        },
        selectedRowKeys: selectedKeys,
      };
    };

    const toUp = (record, index) => {
      if (index > 0) {
        const newTargetKeys = [...state.targetKeys];
        // 交换当前位置与上一个位置
        [newTargetKeys[index], newTargetKeys[index - 1]] = [
          newTargetKeys[index - 1],
          newTargetKeys[index],
        ];
        state.targetKeys = newTargetKeys;
      }
    };

    const toDown = (record, index) => {
      if (index < state.targetKeys.length - 1) {
        const newTargetKeys = [...state.targetKeys];
        // 交换当前位置与下一个位置
        [newTargetKeys[index], newTargetKeys[index + 1]] = [
          newTargetKeys[index + 1],
          newTargetKeys[index],
        ];
        state.targetKeys = newTargetKeys;
      }
    };

    const onFinish = () => {
      if (!state.targetKeys.length) {
        message.error("请选择视频");
        return;
      }
      state.confirmLoading = true;
      const dto = {
        playerId: props.detail.id,
        taskList: state.targetKeys.map((item, index) => {
          return {
            id: item,
            index: index,
          };
        }),
        type: 3,
      };
      clipsVideoTask(dto)
        .then((res) => {
          if (res.result && res.data) {
            message.success("生成成功，请查看浏览器下载");
            emit("submit", res.data);
            emit("cancel");
          } else {
            message.error("生成失败: " + res.msg);
          }
          state.confirmLoading = false;
        })
        .catch(() => {
          message.error("生成内容下载失败: ");
          state.confirmLoading = false;
        });
    };

    const onFinishFailed = (errorInfo) => {
      message.error(errorInfo);
      console.log(errorInfo);
    };

    const uploadFunc = (res) => {
      console.log(res);
    };

    return {
      ...toRefs(state),
      handleCancel,
      handleChange,
      handleSelectChange,
      onFinish,
      onFinishFailed,
      uploadFunc,
      getRowSelection,
      leftColumns,
      rightColumns,
      toUp,
      toDown,
    };
  },
};
</script>

<style lang="scss" scoped>
.table-button {
  .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
</style>
